package com.huajx.tb.handler;

import com.huajx.core.handler.HandlerAdapter;
import com.huajx.core.message.RequestMessage;
import com.huajx.core.message.ResponseMessage;
import com.huajx.core.util.MessageKit;
import com.huajx.tb.dto.NengLongMessage;
import com.huajx.util.date.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.huajx.core.kit.AsyncHttpClientKit;

/**
 * 处理学生进出校门数据
 * <p>
 * 上传进出校信息操作
 * <p>
 * 上传进出校信息语法(由考勤机发给翼校通平台) [08]
 */
public class StudentSchoolRecords extends AbstractNengLongHandler {
    protected final Logger logger = LoggerFactory.getLogger(StudentSchoolRecords.class);

    public static final HandlerAdapter me = new StudentSchoolRecords();

    private final static String controllerKey = "/di/tianbo/record";
//	private final static String controllerKey="http://127.0.0.1:8080/jxt-weixin/di/personsattendance/attendancePersonsData";

    @Override
    public ResponseMessage handler(RequestMessage request) {
        NengLongMessage dto = getMessage(request.getMessage());

        byte[] bytes = dto.getBody();
        logger.info("包体: {}", MessageKit.bytesToString(bytes));

        // 处理卡点数据
        long start = DateUtil.currentSeconds();
        try {
//			if(StrKit.notEmpty(list)){
            AsyncHttpClientKit.post(getServerUrl(controllerKey), MessageKit.bytesToString(bytes), content -> logger.info("请求HTTP处理时长:{},{}", DateUtil.currentSeconds() - start, content));

//				logger.info("Http 请求开始, URL: {}，请求参数：{}", controllerKey, rb.dataToJson());
//				Object obj = HttpKit.post(controllerKey, rb.dataToJson());
//				logger.info("Http 请求结束，请求结果：{}", obj);
//			}
        } catch (Throwable e) {
            logger.error("exceptionCaught()... from " + request.getSession().getRemoteAddress(), e);
            e.printStackTrace();
        }

        render(request.getSession(), dto, "OK");

//		StringBuilder sb = new StringBuilder();
//		String m = MessageKit.getStr(bytes, 3, 23);
//		sb.append("JTP").append(m).append("000408OK61");
////		sb.append("JTP").append(sent.get("serialNo")).append(sent.get("version")).append(deviceId).append("000408OK61");
//
//		logger.info("考勤记录响应: {}", sb.toString());
//		request.getSession().write(sb.toString());
        logger.info("接收数据时长:{}", DateUtil.currentSeconds() - start);
        return null;
    }


//	@Override
//	public ReplyBody process(LdSession session, SentBody sent) {
//		byte[] bytes = sent.getMessage();
//
////		ReplyBody rb = new ReplyBody();
////
////		rb.setKey(sent.getKey());
////
////		logger.info("接收 到的数据:{}",MessageKit.bytesToString(bytes));
////
////		int recordCount = Integer.valueOf(MessageKit.getStr(bytes, 0, 2));
////
////		int recordLen = 39;
////
////		List<Map<String, String>> list = new ArrayList<>();
////		for (int i = 0; i < recordCount; i++) {
////			Map<String, String> record = new HashMap<>();
////
////			//1进校 2 出校 3危险区域
////			try{
////				String optType = MessageKit.getStr(bytes, 2 + i * recordLen + 20 + 12, 1);
////				if("1".equals(optType) || "2".equals(optType) || "3".equals(optType)){
////				}else{
////					continue;
////				}
////				record.put("opt_type", optType);
////			}catch(Throwable e){
////				logger.info("进出校数据获取异常，数据:{}, 截取长度：{}, 数据长度: {}", MessageKit.bytesToString(bytes), 2 + i * recordLen + 20 + 12, bytes.length);
////				continue;
////			}
////
////			try{
////				String start_time = MessageKit.getStr(bytes, 2 + i * recordLen + 20, 12).trim();
////				start_time = DateKit.format(DateKit.parse(start_time, DateKit.pattern_ymdhms), DateKit.pattern_ymd_hms);
////				record.put("start_time", start_time);
////			}catch(Throwable e){
////				logger.info("时间获取异常，数据:{}, 截取长度：{}, 数据长度: {}", MessageKit.bytesToString(bytes), 2 + i * recordLen + 20, bytes.length);
////			}
////
////			record.put("card_id", MessageKit.getStr(bytes, 2 + i * recordLen, 20).trim());
////			list.add(record);
////		}
////		String deviceId = (String)sent.get("device_id");
////		rb.put("device_id", deviceId.trim());
////
////		rb.put("records", list);
////
////		rb.put("total", recordCount);
//
//		logger.info("包体: {}",MessageKit.bytesToString(bytes));
//
////		logger.info("获取到的数据: {}", rb.dataToJson());
//
//		// 处理卡点数据
//		long start = DateKit.getDateByTime();
//		try {
////			if(StrKit.notEmpty(list)){
//				AsyncHttpClientKit.post(controllerKey, MessageKit.bytesToString(bytes), new AsyncHttpClientKit.StringFutureCallback() {
//
//					@Override
//					public void success(String content) {
//						logger.info("请求HTTP处理时长:{}", DateKit.getDateByTime()-start);
//					}
//				});
//
////				logger.info("Http 请求开始, URL: {}，请求参数：{}", controllerKey, rb.dataToJson());
////				Object obj = HttpKit.post(controllerKey, rb.dataToJson());
////				logger.info("Http 请求结束，请求结果：{}", obj);
////			}
//		} catch (Throwable e) {
//			logger.error("exceptionCaught()... from " + session.getRemoteAddress(), e);
//			e.printStackTrace();
//		}
//
//		StringBuilder sb = new StringBuilder();
//		String m = MessageKit.getStr(bytes, 3, 23);
//		sb.append("JTP").append(m).append("000408OK61");
////		sb.append("JTP").append(sent.get("serialNo")).append(sent.get("version")).append(deviceId).append("000408OK61");
//
//		logger.info("考勤记录响应: {}", sb.toString());
//		session.getIoSession().write(sb.toString());
//		logger.info("接收数据时长:{}", DateKit.getDateByTime()-start);
//		return null;
//	}
}
